<template>
	<div>
		<!-- 面包屑 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>用户管理</el-breadcrumb-item>
			<el-breadcrumb-item>用户列表</el-breadcrumb-item>
		</el-breadcrumb>

		<!-- 卡片视图 -->
		<el-card class="box-card">
			<el-row :gutter="20">
				<el-col :span="8">
					<el-input placeholder="请输入内容" v-model="queryInfo.query" class="input-with-select" clearable @clear="getUserList()">
						<el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
					</el-input>
				</el-col>
				<el-col :span="3"><el-button type="primary" @click="addUserDialog = true">添加用户</el-button></el-col>
			</el-row>
			<el-table :data="userslist" border stripe>
				<el-table-column type="index"></el-table-column>
				<el-table-column prop="username" label="姓名" width="180"></el-table-column>
				<el-table-column prop="email" label="邮箱" width="180"></el-table-column>
				<el-table-column prop="mobile" label="电话"></el-table-column>
				<el-table-column prop="role_name" label="角色"></el-table-column>
				<el-table-column prop="mg_state" label="状态">
					<template slot-scope="scope">
						<el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="180px">
					<template slot-scope="scope">
						<el-button type="primary" icon="el-icon-edit" @click="showEdit(scope.row.id)" size="mini"></el-button>
						<el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
						<el-tooltip class="item" effect="dark" content="设置权限" :enterable="false" placement="top-start">
							<el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
						</el-tooltip>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="queryInfo.pagenum"
				:page-sizes="[1, 5, 10]"
				:page-size="queryInfo.pagesize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="total"
			></el-pagination>
		</el-card>
		<el-dialog title="添加用户" :visible.sync="addUserDialog" @close="AddDialogClose">
			<el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="80px">
				<el-form-item label="用户名" prop="username"><el-input v-model="addForm.username" autocomplete="off"></el-input></el-form-item>
				<el-form-item label="密码" prop="password"><el-input v-model="addForm.password" autocomplete="off"></el-input></el-form-item>
				<el-form-item label="邮箱" prop="email"><el-input v-model="addForm.email" autocomplete="off"></el-input></el-form-item>
				<el-form-item label="手机" prop="mobile"><el-input v-model="addForm.mobile" autocomplete="off"></el-input></el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="addUserDialog = false">取 消</el-button>
				<el-button type="primary" @click="addUserDo">确 定</el-button>
			</div>
		</el-dialog>
		<!-- 修改对话框 -->
		<el-dialog title="修改用户" :visible.sync="editUserDialog" @close="editFormClosed">
			<el-form ref="editFormRef" :model="editForm" :rules="editFormRules">
				<el-form-item label="用户名"><el-input v-model="editForm.username" autocomplete="off" disabled></el-input></el-form-item>
				<el-form-item label="邮箱" prop="email"><el-input v-model="editForm.email" autocomplete="off"></el-input></el-form-item>
				<el-form-item label="手机" prop="mobile"><el-input v-model="editForm.mobile" autocomplete="off"></el-input></el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="editUserDialog = false">取 消</el-button>
				<el-button type="primary" @click="editUserDo">确 定</el-button>
			</div>
		</el-dialog>
		<el-dialog title="分配角色" :visible.sync="setRoleDialog" width="50%">
			<div>
				<p>当前的用户:{{ userInfo.username }}</p>
				<p>当前的角色:{{ userInfo.role_name }}</p>
				<p>
					分配新角色:
					<el-select v-model="selectRoleId" placeholder="请选择">
						<el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
					</el-select>
				</p>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="setRoleDialog = false">取 消</el-button>
				<el-button type="primary" @click="setRoleDo()">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>
<script>
export default {
	data() {
		var checkEmail = (rule, value, callback) => {
			const regEmail = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
			if (regEmail.test(value)) {
				return callback();
			}
			callback(new Error('请输入合法邮箱'));
		};
		var checkMobile = (rule, value, callback) => {
			const regEmail = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
			if (regEmail.test(value)) {
				return callback();
			}
			callback(new Error('请输入合法手机号'));
		};
		return {
			userslist: [],
			total: 0,
			queryInfo: {
				query: '',
				pagenum: 1,
				pagesize: 5
			},
			addUserDialog: false,
			addForm: {
				usernmae: '',
				password: '',
				email: '',
				mobile: ''
			},
			editForm: {},
			addFormRules: {
				username: [
					{
						required: true,
						message: '请输入用户名',
						trigger: 'blur'
					},
					{
						min: 3,
						max: 10,
						message: '长度在 3 到 10 个字符',
						trigger: 'blur'
					}
				],
				password: [
					{
						required: true,
						message: '请输入密码',
						trigger: 'blur'
					},
					{
						min: 8,
						max: 18,
						message: '长度在 8 到 18 个字符',
						trigger: 'blur'
					}
				],
				email: [
					{
						required: true,
						message: '请输入邮箱',
						trigger: 'blur'
					},
					{
						validator: checkEmail,
						trigger: 'blur'
					}
				],
				mobile: [
					{
						required: true,
						message: '请输入手机',
						trigger: 'blur'
					},
					{
						validator: checkMobile,
						trigger: 'blur'
					}
				]
			},
			editUserDialog: false,
			editFormRules: {
				username: [
					{
						required: true,
						message: '请输入用户名',
						trigger: 'blur'
					},
					{
						min: 3,
						max: 10,
						message: '长度在 3 到 10 个字符',
						trigger: 'blur'
					}
				],
				email: [
					{
						required: true,
						message: '请输入邮箱',
						trigger: 'blur'
					},
					{
						validator: checkEmail,
						trigger: 'blur'
					}
				],
				mobile: [
					{
						required: true,
						message: '请输入手机',
						trigger: 'blur'
					},
					{
						validator: checkMobile,
						trigger: 'blur'
					}
				]
			},
			selectRoleId: '',
			setRoleDialog: false,
			userInfo: {},
			rolesList: []
		};
	},
	methods: {
		async getUserList() {
			const { data: res } = await this.$http.get('users', {
				params: this.queryInfo
			});
			if (res.meta.status != 200) {
				return this.$message.error(res.meta.msg);
			}
			this.userslist = res.data.users;
			this.total = res.data.total;
		},
		handleSizeChange(newsize) {
			this.queryInfo.pagesize = newsize;
			this.getUserList();
		},
		handleCurrentChange(newpage) {
			this.queryInfo.pagenum = newpage;
			this.getUserList();
		},
		async userStateChange(userInfo) {
			const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`);
			if (res.meta.status != 200) {
				userInfo.mg_state = !userInfo.mg_state;
				return this.$message.error('更新用户状态失败');
			}
			this.$message.success('更新用户状态成功');
		},
		AddDialogClose() {
			this.$refs.addFormRef.resetFields();
		},
		addUserDo() {
			this.$refs.addFormRef.validate(async valid => {
				if (!valid) return;
				const { data: res } = await this.$http.post('users', this.addForm);
				if (res.meta.status !== 201) {
					this.$message.error('添加用户失败');
				}
				this.$message.success('添加用户成功');
				this.addUserDialog = false;
				this.getUserList();
			});
		},
		async showEdit(id) {
			const { data: res } = await this.$http.get('users/' + id);
			if (res.meta.status !== 200) {
				return this.$message.error('查询用户信息失败');
			}
			this.editForm = res.data;
			this.editUserDialog = true;
		},
		editFormClosed() {
			this.$refs.editFormRef.resetFields();
		},
		editUserDo() {
			this.$refs.editFormRef.validate(async valid => {
				if (!valid) return;
				const { data: res } = await this.$http.put('users/' + this.editForm.id, {
					email: this.editForm.email,
					mobile: this.editForm.mobile
				});
				if (res.meta.status !== 200) {
					return this.$message.error('更新用户信息失败');
				}

				this.editUserDialog = false;
				this.getUserList();
				this.$message.success('更新用户信息成功');
			});
		},
		deleteUser(id) {
			this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(async () => {
					const { data: res } = await this.$http.delete('users/' + id);
					if (res.meta.status !== 200) {
						return this.$message.error('删除用户失败');
					}
					this.$message.success('删除用户成功');
					this.getUserList();
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
		},
		async setRole(userinfo) {
			this.userInfo = userinfo;
			const { data: res } = await this.$http.get('roles');
			if (res.meta.status != 200) {
				return this.$message.error('获取角色列表失败');
			}
			this.rolesList = res.data;
			this.setRoleDialog = true;
		},
		async setRoleDo() {
			if (!this.selectRoleId) {
				return this.$message.error("请选择角色");
			}
			const {
				data: res
			} = await this.$http.put(`users/${this.userInfo.id}/role`, {
				rid: this.selectRoleId
			});
			if (res.meta.status != 200) {
				return this.$message.error("更新角色失败");
			}
			this.$message.success("更新角色成功");
			this.getUserList();
			this.setRoleDialog = false;
		}
	},
	created() {
		this.getUserList();
	}
};
</script>
<style scoped></style>
